package com.example.event_resource_java.authority.controller.CommonController;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.example.event_resource_java.commons.enums.Constants;
import com.example.event_resource_java.starinside.redis.RedisTime;
import com.example.event_resource_java.starinside.redis.RedisUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @ClassName CaptchaController
 * @Description: 图形验证码
 * @Author: 艾凯
 * @CreateDate: 2024/4/3 15:01
 * @UpdateUser: 更新人
 * @UpdateDate: 2024/4/3 15:01
 * @UpdateRemark:
 * @Version: 1.0
 */

@RestController
@RequestMapping("/code")
public class CaptchaController {

    /**
     * @auther: ak
     * @Description 生成线形干扰的0-9四位随机验证码
     * @param:
     * @return:
     * @date: 2024/4/3 15:01
     */
    @CrossOrigin
    @GetMapping("/getCaptcha")
    public void getCap(HttpServletResponse response) {

        // 随机四位验证码
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);

        // 设置验证码图片高 宽 字符个数 干扰线条数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 30, 4, 20);
        //lineCaptcha.setBackground(Color.gray);

        // 将生成的验证码存入redis中 key: uuid value: verifyCode
        String uuid = UUID.randomUUID().toString();
        String verifyKey = Constants.CAPTCHA_CODE_KEY;

        // captcha_codes:uuid, code, 5min
        RedisUtil.set(verifyKey + uuid, lineCaptcha.getCode(), RedisTime.redisTimeF / 6);
        //RedisUtil.set(verifyKey + uuid, lineCaptcha.getCode());

        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        // 存放用户uuid
        response.setHeader("uuid", uuid);
        response.setHeader("Access-Control-Expose-Headers", "uuid");

        try {
            lineCaptcha.setGenerator(randomGenerator);
            lineCaptcha.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
            // return ApiResult.fail(EnumErrorCode.userLoginFai1l2.getCode(), EnumErrorCode.userLoginFai1l2.toString());
        }
        //return ApiResult.success();
    }


}
